package com.fort.teachermanagementsys.springsecurity.handler;



import com.fort.teachermanagementsys.springsecurity.config.JWTConfig;
import com.fort.teachermanagementsys.springsecurity.entity.SelfUserEntity;
import com.fort.teachermanagementsys.springsecurity.util.JWTTokenUtil;
import com.fort.teachermanagementsys.springsecurity.util.ResultUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description 登录成功处理类
 * @Author Allen
 * @CreateTime 2024/4/2 10:45
 */
@Slf4j
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 登录成功返回结果
     * @Author Allen
     * @CreateTime 2024/4/2 10:47
     */
    @Override
    public void onAuthenticationSuccess(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 组装JWT
        SelfUserEntity selfUserEntity =  (SelfUserEntity) authentication.getPrincipal();
        String token = JWTTokenUtil.createAccessToken(selfUserEntity);
        token = JWTConfig.tokenPrefix + token;
        // 封装返回参数
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code",200);
        resultData.put("msg", "登录成功");
        resultData.put("token",token);
        resultData.put("username", selfUserEntity.getUsername());
        ResultUtil.responseJson((HttpServletResponse) response,resultData);
    }
}
